package com.guit.hrms.utils;

import java.time.Duration;
import java.time.LocalTime;

public class TimeDifferenceUtil {

    /**
     * 计算时间差
     * @param before 前一个时间
     * @param after 后一个时间
     * @return LocalTime格式的时间差
     */
    public static LocalTime compute(LocalTime before,LocalTime after){
        // 计算时间差
        Duration duration = Duration.between(before, after);

        // 获取时间差的各个部分
        long hours = duration.toHours();
        long minutes = duration.toMinutes() % 60;
        long seconds = duration.getSeconds() % 60;

        // 将时间差转换为 LocalTime 并返回
        return LocalTime.of((int) hours, (int) minutes, (int) seconds);
    }

    /**
     * 将 Duration 格式化为 HH:mm:ss（支持超过 24 小时）
     */
    private static String formatDuration(Duration duration) {
        long totalSeconds = duration.getSeconds();
        long hours = totalSeconds / 3600;
        long minutes = (totalSeconds % 3600) / 60;
        long seconds = totalSeconds % 60;
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }

    /**
     * 将 HH:mm:ss 字符串解析为 Duration
     */
    private static Duration parseDuration(String time) {
        String[] parts = time.split(":");
        long hours = Long.parseLong(parts[0]);
        long minutes = Long.parseLong(parts[1]);
        long seconds = Long.parseLong(parts[2]);
        return Duration.ofHours(hours).plusMinutes(minutes).plusSeconds(seconds);
    }

    /**
     * 累加两个 HH:mm:ss 格式的时间
     */
    public static String addTimes(String time1, String time2) {
        Duration duration1 = parseDuration(time1);
        Duration duration2 = parseDuration(time2);
        Duration total = duration1.plus(duration2);
        return formatDuration(total);
    }
}
